package laf.behaviours;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Logger;

import jade.content.lang.Codec.CodecException;
import jade.content.onto.OntologyException;
import jade.core.AID;
import jade.core.Agent;
import jade.core.behaviours.OneShotBehaviour;
import jade.domain.DFService;
import jade.domain.FIPAException;
import jade.domain.FIPANames;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.SearchConstraints;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import laf.agents.CognitiveAgent;
import laf.lang.Describes;
import laf.onto.LAFOntology;

public class BroadcastDescriptionBehaviour extends OneShotBehaviour {

	/**
	 * 
	 */
	private static final long serialVersionUID = 6623441690444623361L;
	private Describes description;

	public BroadcastDescriptionBehaviour(CognitiveAgent agent, Describes description) {
		super(agent);
		this.description = description;
	}

	@Override
	public void action() {
		ACLMessage msg = new ACLMessage(ACLMessage.INFORM);

		Collection<AID> receivers = searchDF(CognitiveAgent.SERVICE_TYPE);
		if (receivers.size() == 0) {
			// TODO Warning: No receivers
			return;
		}

		for (AID aid : receivers) {
			msg.addReceiver(aid);
		}

		msg.setLanguage(FIPANames.ContentLanguage.FIPA_SL);
		msg.setOntology(LAFOntology.NAME);
		try {
			myAgent.getContentManager().fillContent(msg, description);
			myAgent.send(msg);
			((CognitiveAgent) myAgent).getLogger().info("Broadcasting description");
			((CognitiveAgent) myAgent).getLogger().fine(msg.toString());
		} catch (CodecException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (OntologyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	protected Collection<AID> searchDF(String service) {
		DFAgentDescription dfd = new DFAgentDescription();
		ServiceDescription sd = new ServiceDescription();
		sd.setType(service);
		dfd.addServices(sd);

		SearchConstraints all = new SearchConstraints();
		all.setMaxResults(new Long(-1));

		List<AID> aidList = new ArrayList<AID>();
		AID aid;
		try {
			for (DFAgentDescription agentDesc : DFService.search(myAgent, dfd, all)) {
				aid = agentDesc.getName();
				if (!aid.equals(myAgent.getAID())) {
					aidList.add(aid);
				}
			}
		} catch (FIPAException fe) {
			fe.printStackTrace();
		}
		return aidList;
	}
}
